package com.juzipi.demo.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.juzipi.demo.pojo.Resource;
import com.juzipi.demo.pojo.Role;
import com.juzipi.demo.pojo.RoleResource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义授权
 */

@Service
public class AuthService {


//    @Autowired
//    private ResourceMapper resourceMapper;
//    @Autowired
//    private RoleMapper roleMapper;
//    @Autowired
//    private RoleResourceMapper roleResourceMapper;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleResourceService roleResourceService;


    public boolean isAccess(HttpServletRequest request, Authentication authentication){
        String requestURI = request.getRequestURI();
        List<Role> rolesForResource = getRolesForResource(requestURI);
        if (CollectionUtils.isNotEmpty(rolesForResource)){
            for (Role role : rolesForResource){
                //授予权限,根据用户信息里的权限,匹配就返回true
                for (GrantedAuthority grantedAuthority : authentication.getAuthorities()){
                    if (role.getAuthority().equals(grantedAuthority.getAuthority())){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //根据 resource获取角色的role
    private List<Role> getRolesForResource(String requestURI) {
        if (StringUtils.isBlank(requestURI)){
            return Collections.emptyList();
        }
        //根据uri查询出 resource
//        Resource resource = resourceMapper.selectOne(new QueryWrapper<Resource>().lambda().eq(Resource::getUrl, requestURI));
        Resource resource = resourceService.queryResourceByUri(requestURI);
        if (resource == null){
            return Collections.emptyList();
        }
        //根据 resource的id查询中间表
//        List<RoleResource> roleResources = roleResourceMapper.selectList(new QueryWrapper<RoleResource>().lambda().eq(RoleResource::getResourceId, resource.getId()));
        List<RoleResource> roleResources = roleResourceService.queryRoleResourceList(resource.getId());
        if (CollectionUtils.isEmpty(roleResources)){
            return Collections.emptyList();
        }
        //把查询出的中间表的 roleId 做一个集合
        List<Long> roleIds = roleResources.stream().map(RoleResource::getRoleId).collect(Collectors.toList());
        //根据roleId集合查询用户角色
        return roleService.queryRoleList(roleIds);
    }
}
